<template>
  <div class="app-container">
    <upload-excel-component :on-success="handleSuccess" :before-upload="beforeUpload" />
    <el-table :data="tableData" border highlight-current-row style="width: 100%;margin-top:20px;">
      <el-table-column v-for="item of tableHeader" :key="item" :prop="item" :label="item" />
    </el-table>
  </div>
</template>

<script>
import UploadExcelComponent from '@/components/UploadExcel/index.vue'
import { addEmployeeBatch } from '@/api/employees'
import { formatExcelDate } from '@/utils/index'

export default {
  name: 'Import',
  components: { UploadExcelComponent },
  data() {
    return {
      tableData: [],
      tableHeader: []
    }
  },
  methods: {
    beforeUpload(file) {
      const isLt1M = file.size / 1024 / 1024 < 1

      if (isLt1M) {
        return true
      }

      this.$message({
        message: 'Please do not upload files larger than 1m in size.',
        type: 'warning'
      })
      return false
    },
    handleSuccess({ results, header }) {
      this.tableData = results
      this.tableHeader = header
      const data = this.transToExcel(results)
      this.doAdd(data)
    },
    async doAdd(data) {
      try {
        const res = await addEmployeeBatch(data)
        console.log('addEmployeeBatch', res)
        this.$router.back()
      } catch (err) {
        console.log('addEmployeeBatch', err)
      }
    },
    transToExcel(data) {
      const mapInfo = {
        '入职日期': 'timeOfEntry',
        '手机号': 'mobile',
        '姓名': 'username',
        '转正日期': 'correctionTime',
        '工号': 'workNumber',
        '部门': 'departmentName'

      }
      const result = data.map(zhObj => {
        // zhObj==>  {
        // 入职日期: 44505,
        // 姓名: "小张",
        // 工号: "9002",
        // 手机号: "13800000252",
        // 转正日期: 44892,
        // 部门: "总裁办"
        // },
        const enkeyObj = {} // 存储英文的key的数据  {'timeOfEntry': 44505}
        const zhKeys = Object.keys(zhObj) // ['入职日期', '姓名', '工号', '手机号', '转正日期', '部门']

        zhKeys.forEach(zhKey => {
          // 根据中文的key获取到英文的key
          const enKey = mapInfo[zhKey]
          if (enKey === 'timeOfEntry' || enKey === 'correctionTime') {
            enkeyObj[enKey] = formatExcelDate(zhObj[zhKey])
          } else {
          //   console.log(zhKey)
            enkeyObj[enKey] = zhObj[zhKey]
          }
        })

        return enkeyObj
      })
      return result
    }
  }
}
</script>
